package com.beiyou.controller;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.beiyou.dao.TukuDao;
import com.beiyou.model.Tuku;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/imgserver-api")
public class TukuController {

    @Value("${web.uploadPath}")
    private String baseUploadPath;

    @Value("${web.url}")
    private String imgUrl;

    @Autowired
    private TukuDao tukuDao;

    @GetMapping("/select")
    public List<Tuku> select(){
        return tukuDao.select();
    }

    @PostMapping("/upload")
    public Integer uploadImg(@RequestBody Tuku tuku){
        String base64String = tuku.getBase64();
        String[] dataArray = StrUtil.splitToArray(base64String, "base64,");
        byte[] bytes = Base64Decoder.decode(dataArray[1]);
        String name = IdUtil.simpleUUID()+"_"+tuku.getName();
        FileUtil.writeBytes(bytes,baseUploadPath+name);

        tuku.setName(name);
        tuku.setImg(imgUrl+"/images/"+name);
        tukuDao.insert(tuku);
        return  1;
    }
}
